class EventEmitter {
    constructor() {
        this._event = Object.create(null)
    }

    on(type, handler) {
        (this._event[type] || (this._event[type] = [])).push(handler)
    }

    off(type, handler) {
        if (this._event[type]) {
            this._event[type].splice(this._event[type].indexOf(handler), 1)
        }
    }

    emit(type) {
        // 将参数转化为数组
        let payload = Array.prototype.slice.call(arguments, 1)
        let array = this._event[type] || []

        for (let i = 0; i < array.length; i++) {
            let handler = this._event[type][i]
            handler.apply(this, payload)
        }
    }
}

var obj = new EventEmitter()
obj.on('hello',function (a,b) {
    console.log(a,b)
})
obj.emit('hello',1,2)
//取消订阅事件的回调必须是具名函数
obj.on('test',fn1 = function () {
    console.log('fn1')
})
obj.on('test',fn2 = function () {
    console.log('fn2')
})
obj.off('test',fn1)
obj.emit('test')